package com.example.himalaya.adapters;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.himalaya.R;
import com.ximalaya.ting.android.opensdk.model.word.QueryResult;

import java.util.ArrayList;
import java.util.List;

public class SuggestWordListRvAdapter extends RecyclerView.Adapter<SuggestWordListRvAdapter.ViewHlder>{

    private OnItemClickListener mOnItemClickListener;

    public class ViewHlder extends RecyclerView.ViewHolder {

        private  TextView mSuggestswordTv;

        public ViewHlder(@NonNull View itemView) {
            super(itemView);
            mSuggestswordTv = itemView.findViewById(R.id.search_suggestword_item);
        }

            public void setData(QueryResult queryResult) {
                mSuggestswordTv.setText(queryResult.getKeyword());
            }
        }

    private List<QueryResult> mSuggestWordsList = new ArrayList<>();
    @SuppressLint("NotifyDataSetChanged")
    public void setData(List<QueryResult> suggestWordsList) {
        if (suggestWordsList != null) {
            this.mSuggestWordsList.clear();
            this.mSuggestWordsList.addAll(suggestWordsList);
            notifyDataSetChanged();
        }
    }



    @NonNull
    @Override
    public ViewHlder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_suggest_word, parent, false);
        return new ViewHlder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHlder holder, int position) {
        holder.itemView.setTag(position);
        holder.setData(mSuggestWordsList.get(position));
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mOnItemClickListener.onItemClick(mSuggestWordsList.get((Integer) holder.itemView.getTag()).getKeyword());
            }
        });
    }

    @Override
    public int getItemCount() {
        if (mSuggestWordsList != null) {
            return mSuggestWordsList.size();
        }
        return 0;
    }

    public interface OnItemClickListener{
        void onItemClick(String keyword);
    }
    public void setOnItemClickListener(OnItemClickListener onItemClickListener){
        this.mOnItemClickListener = onItemClickListener;
    }

}
